package org.itcast.travel.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.itcast.travel.exception.VoteNotAllowedExcepton;
import org.itcast.travel.mapper.RaceMapper;
import org.itcast.travel.mapper.RaceVotesMapper;
import org.itcast.travel.pojo.PageBean;
import org.itcast.travel.pojo.Race;
import org.itcast.travel.pojo.RaceQueryParam;
import org.itcast.travel.pojo.RaceVotes;
import org.itcast.travel.service.RaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class RaceServiceImpl implements RaceService {
    @Autowired
     private RaceMapper raceMapper;
    @Autowired
    private RaceVotesMapper raceVotesMapper;
    //比赛报名
    @Override
    public void enrollFor(Race race) {
        //补充参数
        race.setCreateTime(LocalDateTime.now());
        race.setUpdateTime(LocalDateTime.now());
        raceMapper.insert(race);

    }
    //修改比赛信息
    @Override
    public void update(Race race) {
        //补充数据
        race.setUpdateTime(LocalDateTime.now());
        raceMapper.updateByPrimaryKey(race);
    }

    @Override
    public Race getByid(Integer id) {
        return raceMapper.selectByPrimaryKey(id);
    }

    @Override
    public Object page(RaceQueryParam raceQueryParam) {
        //自动分页
        PageHelper.startPage(raceQueryParam.getPage(), raceQueryParam.getPageSize());
        //获取数据
        Page<Race> races = raceMapper.page(raceQueryParam);
        //封装数据
        Page<Race> page = races;
        //返回数据
        return new PageBean(page.getTotal(), page.getResult());
    }

    @Override
    public void delete(Integer id,Integer raceId) {
        raceMapper.deleteByPrimaryKey(id);
        raceMapper.deleteVotesByRaceId(raceId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void vote(Integer userId, Integer raceId) throws VoteNotAllowedExcepton {
        raceMapper.updateVotes(raceId);

        List<RaceVotes> list =raceVotesMapper.selectOne(userId,raceId);

        if (list.size() >0 && list != null){
            //已投票，抛异常
          throw new VoteNotAllowedExcepton("去你的，投完了还想投");
        }else {
            raceVotesMapper.insertLike(userId, raceId);
        }

    }


}
